import axios from 'axios';
import { useEffect, useState, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input ,message} from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
const Master = () => {
  const [form] = useForm();
  const [nodata, setnoData] = useState("1");
  const [data, setData] = useState([]);
  const [length, setlength] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editedData, setEditedData] = useState(null);
  const [params,setParams] = useState({
    page:1,
    perpage:5
  })
  const [searchInput, setSearchInput] = useState('');
  const isAlertShownRef = useRef(false);
  useEffect(() => {
    let isSubscribed = true;
    const studentid = localStorage.getItem('studentid');
    axios.get('http://localhost:8000/getchoosedcourselist',{   params: {
        ...params, // 将 params 对象展开，添加到 params 字段中
        studentid
      }})
      .then(response => {
        if (isSubscribed) { // 在更新状态之前检查组件是否仍然订阅
          if (typeof response.data === 'string' && !isAlertShownRef.current) {
            isAlertShownRef.current = true;
            Modal.error({
              title: '非退课时间',
              content: '现在是非退课时间',
              okText: '确定',
              onOk() {
              }
            });
            setnoData("2");
        } else {
        console.log(response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
        // 等待setData执行完毕后再打印data
        console.log("Updated data:", data);
        }}
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
      return () => {
        isSubscribed = false; // 当组件卸载时取消订阅
      };
  }, [params]);
  

  // 翻页实现
  const pageChange = (page) => {
    setParams({
      ...params,
      page
    })
  }



  const Deselect = (data) => {
    const studentid = localStorage.getItem('studentid');
    console.log(data.courseid,studentid);
    axios.post('http://localhost:8000/Deselectcourse', {
      courseid: data.courseid,
      studentid: studentid,
    })
    .then(response => {
      // 请求成功的处理逻辑
      console.log('后端返回的数据:', response.data);
      message.success('课程删除成功')
        const studentid = localStorage.getItem('studentid');
        axios.get('http://localhost:8000/getchoosedcourselist',{   params: {
            ...params, // 将 params 对象展开，添加到 params 字段中
            studentid
          }})
          .then(response => {
            console.log(response.data.list);
            setData(response.data.list);
            setlength(response.data.length);
            // 等待setData执行完毕后再打印data
            console.log("Updated data:", data);
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
    })
    .catch(error => {
      // 请求失败的处理逻辑
      console.error('请求失败:', error);
    });
  }


  const columns = [
    {
      title: '课程编号',
      dataIndex: 'courseid',
      width: 120
    },
    {
      title: '课程',
      dataIndex: 'coursename',
    },
    {
      title: '教室',
      dataIndex: 'location'
    },
    {
      title: '开课学期',
      dataIndex: 'term'
    },
    {
      title: '上课时间',
      dataIndex: 'time'
    },
    {
      title: '课时',
      dataIndex: 'number'
    },
    {
      title: '开课学院',
      dataIndex: 'college'
    },{
      title: '属性',
      dataIndex: 'attribute'
    },
    {
      title: '最大学生数量',
      dataIndex: 'studentnum'
    },
    {
      title: '当前学生数量',
      dataIndex: 'num'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<DeleteOutlined/>}
              onClick={() => Deselect(data)} 
            />
          </Space>
        )
      },
      fixed: 'right'
    }
  ]

  return (
    <div>
      <h1>Course Page</h1>
      <Card title={`根据筛选条件共查询到 ${length} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={
            {
              pageSize: params.perpage,
              onChange: pageChange,
              current: params.page,
              total: length
            }
          }
        />
      </Card>

    </div>
  );
};


export default Master